package com.icesoft.core.common.log;

import java.io.File;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.lang3.SystemUtils;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

/**
 * 定义Logfilter拦截输出日志
 * 
 * @author jie
 * @date 2018-12-24
 */
public class LogFilter extends Filter<ILoggingEvent> {
	public static volatile boolean USED = false;

	public static volatile String PATH = null;

	private static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

	private static final String PathParamName = "path";

	@Override
	public FilterReply decide(ILoggingEvent event) {
		if (USED) {
			String msg = event.getFormattedMessage();
			IThrowableProxy throwableProxy = event.getThrowableProxy();
			if (throwableProxy != null) {
				msg = msg + "\n" + ThrowableProxyUtil.asString(throwableProxy);
			}
			LogMessage loggerMessage = new LogMessage(msg,
					DateFormat.getDateTimeInstance().format(new Date(event.getTimeStamp())), event.getThreadName(),
					event.getLoggerName(), event.getLevel().levelStr);
			LoggerQueue.getInstance().push(loggerMessage);
		}
		if (PATH == null) {
			if (atomicBoolean.compareAndSet(false, true)) {
				try {
					PATH = event.getLoggerContextVO().getPropertyMap().get(PathParamName);
					File logFile = new File(PATH);
					if (!logFile.exists()) {
						PATH = SystemUtils.USER_DIR + "/" + PATH;
						logFile = new File(PATH);
					}
					PATH = logFile.getCanonicalPath();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (PATH == null) {
					System.err.println("logback-spring.xml中未找到springProperty配置：" + PathParamName);
					System.exit(0);
				}
			}
		}
		return FilterReply.ACCEPT;
	}

	public static String getLogFilePath() {
		return PATH;
	}
}